package org.scohen.juploadr.app.scalers;

import java.awt.Graphics2D;
import java.awt.GraphicsEnvironment;
import java.awt.RenderingHints;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

import org.eclipse.swt.graphics.Point;

public class ImageIOScaler extends Scaler {

    public void doScale(File original, File scaled, Point newSize) {
        try {

            ImageIO.setUseCache(true);
            BufferedImage originalImage = ImageIO.read(original);
          
            double scaleFactor = (double) newSize.y / originalImage.getHeight();
            
             BufferedImage scaledImage =
             GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice()
             .getDefaultConfiguration().createCompatibleImage(newSize.x,
             newSize.y);
             Graphics2D gfx = scaledImage.createGraphics();
            
             gfx.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
             RenderingHints.VALUE_INTERPOLATION_BILINEAR);
             AffineTransform at =
             AffineTransform.getScaleInstance(scaleFactor, scaleFactor);
             gfx.drawImage(originalImage, at, null);
             ImageIO.write(scaledImage, getFormatNameFromFile(original),
             scaled);
             gfx.dispose();
 
        } catch (IOException e) {

            e.printStackTrace();
        }
    }

    private String getFormatNameFromFile(File original) {
        return "jpeg";
    }
    
    public boolean isOptimal() {
        return true;
    }
}
